package net.qhzw.geologr5.gis.service.system.component;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import net.qhzw.geologr5.gis.service.system.model.BodyParam;
import net.qhzw.geologr5.gis.service.system.model.HeaderParam;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class ApplyBorrowingLst {


    @Value("${addressDoc}")
    private String addressDoc;

    @Autowired
    private FileTemplate fileTemplate;


    /***
     * 生成插入数据后的Word文件
     */
    public String exportAnnualReport(HeaderParam param1, List<BodyParam> param2, String flag, String filename) {
        try {

            File file = writeAnnualReport(param1, param2, flag, filename);
            //file转 multipartFile
            FileInputStream inputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
            String filePath = fileTemplate.fileUpload(multipartFile);
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }





    /*public void exportAnnualReport(HttpServletResponse response, HeaderParam param1, List<BodyParam> param2, String flag, String filename) {
     *//**
     * 流下载
     *//*
        BufferedInputStream inputStream = null;
        BufferedOutputStream outputStream = null;
        try {
            //获取写入数据后的文件
            File file = writeAnnualReport(param1, param2, flag, filename);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/msword");//设置内容类型为Word格式
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));

            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[inputStream.available() + 1024];
            int num = 0;
            *//**
     * 将数据读取到缓冲区中，再将缓冲区中数据传输出去
     *//*
            while ((num = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, num);
            }
            inputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
*/

    /****
     * 写入
     */
    private File writeAnnualReport(HeaderParam param1, List<BodyParam> param2, String flag, String filename) {
        List<BodyParam> list = new ArrayList<>();
        for (int i = 0; i < param2.size(); i++) {
            BodyParam tem = param2.get(i);
            BodyParam bodyParam = new BodyParam();
            bodyParam.setIndex(i + 1);
            bodyParam.setLevel(tem.getLevel());
            bodyParam.setFilename(tem.getFilename());
            list.add(bodyParam);
        }
        Map<String, Object> fileData = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        //applyDate  hdr
        dataMap.put("applyDate", param1.getApplyDate());
        dataMap.put("applyNo", param1.getApplyNo());
        dataMap.put("total", list.size());
        //表头信息
        fileData.put("data", dataMap);
        //表体信息
        fileData.put("dataList", list);
        File file = new File(filename);
        try {
            Configuration configuration = new Configuration(new Version("2.3.0"));
            configuration.setDefaultEncoding("utf-8");
            configuration.setDirectoryForTemplateLoading(ResourceUtils.getFile("classpath:template"));
            Template template = null;
            if (flag.equals("1")) {
                template = configuration.getTemplate("11.ftl", "utf-8");
            } else if (flag.equals("2")) {
                template = configuration.getTemplate("22.ftl", "utf-8");
            }
            //构造一个向目标文件写的流
            Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            //将数据填充到模板并写入目标文件
            template.process(fileData, writer);
            //写完关闭流
            writer.close();
        } catch (Exception e) {
            return null;
        }
        return file;
    }


    public static void main(String[] args) throws IOException, TemplateException {
        ApplyBorrowingLst applyBorrowingLst = new ApplyBorrowingLst();

        HeaderParam header = new HeaderParam();
        header.setApplyDate(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
        header.setApplyNo("11111111111111");

        List<BodyParam> bodys = new ArrayList();
        for (int i = 1; i <= 21; i++) {
            BodyParam body = new BodyParam();
            body.setFilename("我是文件我是文件我是文件我是文件我是文件" + i);
            body.setLevel("国家级" + i);
            bodys.add(body);
        }
        //applyBorrowingLst.test1(header, bodys, "2");

    }
}